<?php
/**
 * @author wyl
 * @date 2015-8-25 11:47:03
 */
Yii::import('dao.bidAuction.AuctionLimitDao');
Yii::import('application.components.autobid.*');
Yii::import('application.components.auctionCache.AuctionHistoryList');
Yii::import('application.components.auctionCache.customerCacheAuctionBidInfo');
Yii::import('dao.ajax.*');
Yii::import('dao.auction.AuctionDao');
class AjaxController extends Controller{
    
    public function actionAuctionData(){
        Yii::import('dao.auction.AuctionCacheData');
        $ajax = new AuctionDataAjax();        
        $ajax->setRequest($_POST);
        if ($ajax->validate()){
            $auctionData = new AuctionCacheData();
            $rData = $auctionData->findModifyAllByPkGNC($ajax->ids,$ajax->ver);            
            $newData=Yii::app()->tools->modelsToArray($rData,array('id','status','end_time','winner_price','winner_id','winner_name','winner_avatar'));
            if ($ajax->type[0] == 'detail'){
                $auctionId = $ajax->type[1]['auctionId'];
                foreach ($newData as $dataKey => $newDataRow){
                    if ($newDataRow['id'] == $auctionId){
                        $newData[$dataKey]['type'] = 'detail';
                        $bidHistory=new AuctionHistoryList();
                        $bidHistory->setHistoryKey($auctionId);
                        $rHistory=$bidHistory->getHistoryList();
                        $newData[$dataKey]['rBidHistory'] = $rHistory;
                        
                        if (!Yii::app()->user->isGuest){
                            $customerBidInfoCache=new customerCacheAuctionBidInfo();
                            $customerBidInfoCache->customerId=Yii::app()->user->id;
                            $customerBidInfoCache->auctionId=$auctionId;
                            $customerBidInfoData=$customerBidInfoCache->getItems();
                            $newData[$dataKey]['customerBidAuctionInfo'] = $customerBidInfoData;
                        }
                        
                    }
                }
            }
            $ajax->setResponse('rData',$newData);
            $ajax->setResponse('t',time());
            $ajax->setResponse('ver', time());
            
        }
        echo $ajax->response();
    }
    
    //processor 
    public function actionShelfData(){
        $request = $_POST;
        $response = array();
        foreach ($request as $shelfName => $shelf){
            $auctionPool = new AuctionPoolProvider();
            $auctionPool->limit = $shelf['needs'];
            if (!empty( $shelf['noIds'])){
                $ids = explode('|',$shelf['noIds']);
                $auctionPool->not_ids = $ids;
            }
            if(!empty($shelf['checkData'])){
                $auctionPool->attributes = $shelf['checkData'];
            }
            $auctionPool->search_end_time = $shelf['endTime'];

            $auctionPoolData = $auctionPool->search()->getData();
            if(!empty($auctionPoolData)){
                $response[] = array(
                    'name' => $shelf['name'],
                    'data' => Yii::app()->tools->modelsToArray($auctionPoolData),
                );
            }

        }
        echo json_encode($response);
    }
    
    /**
     *  获取auction显示在主站
     */
    public function  actionShelfDataForFeature(){
        $request = $_POST;
        $response = array();
        foreach ($request as $shelfName => $shelf){
            $auctionPool = new AuctionPoolProvider();
            $auctionPool->limit = 16;
            if (!empty( $shelf['noIds'])){
                $ids = explode('|',$shelf['noIds']);
                $auctionPool->not_ids = $ids;
            }
            if(!empty($shelf['checkData'])){
                $auctionPool->attributes = $shelf['checkData'];
            }
            $auctionPool->search_end_time = $shelf['endTime'];
        
            $auctionPoolData = $auctionPool->search()->getData();
            if(!empty($auctionPoolData)){
                $response[] = array(
                    'name' => $shelf['name'],
                    'data' => Yii::app()->tools->modelsToArray($auctionPoolData),
                );
            }
        
        }
        echo json_encode($response);
    }
    
    
    public function actionReturncategory2(){
          $list_two=categorycategoryrelations::model()->findAllByAttributes(array('parent_category_id'=>$_POST['category_parent_id']));
          $echo='';
          foreach ($list_two as  $v) {
          $echo.='<li><a href='.Yii::app()->baseUrl . '/c-'.urlencode(preg_replace('# #', '',preg_replace('#/#', '',$v->category->title))).'-'.$v->category->id.' onmouseover="list3('.$v->category->id.')">'.$v->category->title.'</a></li>';
          }
          echo $echo;
    }
    public function actionReturncategory3(){
          $list_thr=categorycategoryrelations::model()->findAllByAttributes(array('parent_category_id'=>$_POST['category_parent_id']));
          $echo='';
          foreach ($list_thr as  $v) {
            // var_dump($v->category_id);exit;
          $echo.='<li><a href='.Yii::app()->baseUrl . '/c-'.urlencode(preg_replace('# #', '',preg_replace('#/#', '',$v->category->title))).'-'.$v->category->id.'>'.$v->category->title.'</a></li>';
          }
          // var_dump($echo);exit;
          echo $echo;
    }
    
    public function actionActivateautobid(){
        if(!empty($_POST)){
            $form=new AutoBidForm();
            $form->attributes=$_POST;
            $result=array('result'=>"open error");
            $autobid=new AutoBidDao();
            if ($form->validate()) {
                $autobid->customerId=$form->customer_id;
                $autobid->auctionId=$form->auction_id;
                $rs=$autobid->add($form->amount,$form->start_price);
                if ($rs){
                    $result['result']="eGunner says:"."\n"."Auto-Bid Activated!";
                }
            }else{
                $errorMsg=$form->getErrors();
                $errorMsg = array_shift($errorMsg);
                $result['result']=$errorMsg[0];
            }
            echo json_encode($result);
        }
    }
    
    public function actionAutobiddata(){
    	if(!empty($_POST)){
    		$form=new AutoBidForm();
    		$form->attributes=$_POST;
    		
    		$auctionLimit = new AuctionLimitDao();
    		$auctionLimit->auctionId = $form->auction_id;
    		$auctionLimit->customerId = $form->customer_id;
    		$autobid=new AutoBidDao();
    		$autobid->setPrimaryKey($form->auction_id,$form->customer_id);
    		
    		switch ($_POST['status']){
    			case 'off':
    				$auctionLimit->deleteLimit(AuctionLimitDao::AUTO_BID_LIMIT);
    				$autobid->delAutoBid();
    				echo json_encode(array('status'=>'off','success'=>1));
    				break;
    			case 'on' :
    				if (!$form->validate()) {
    					echo json_encode(array('error'=>$form->getErrors()));
    					return false;
    				}
    				$auctionLimit->add($form->end_time,AuctionLimitDao::AUTO_BID_LIMIT);
    				$autobid->add($form->amount);
    				echo json_encode(array('status'=>'on','success'=>1));
    				break;
    		}
    	}
    }
    
    public function actionAutobidstatus(){
    	if(!empty($_POST)){
    		$autobid=new Autobid();
    		$autobid=$autobid->findByPk($_POST['auction_id'].':'.$_POST['customer_id']);
    		if(!empty($autobid)){
    			echo json_encode(array('status'=>'on','amount'=>$autobid->amount));die;
    		}
    		echo json_encode(array('status'=>'off'));
    	}	
    }
    
    public function actionAjaxbuyitnow(){
        $result_array = array('error'=>'You can not buy it now');
    	$request=$_POST; 
    	
    	if (Yii::app()->user->isGuest){
    		$result_array['nologin']='You must be login!';
    		echo json_encode($result_array);
    		return ;
    	}else{
    		$customerId=Yii::app()->user->id;
    	}
        
    	if (!empty($request)){
        	$auctionparame=new AuctionDao();
        	$auctionparame->find($request['auction_id']);
        	if (!$auctionparame->bin){
        	    $result_array=array('error'=>'The Auction can not buy it now!');
        	    echo json_encode($result_array);
        	    return false;
        	}
    	}
    	
        if(!empty($request)){
            //判断auction状态
            $auctioninfo = new AuctionInfo();
            $auctioninfo_data = $auctioninfo->findByAttributes(array('id' => $request['auction_id']));
            $winner_id = 0;
            if(!empty($auctioninfo_data)){
                if($auctioninfo_data->status==1){
                    $auctionpool= new AuctionPool();
                    $auctionpool_data=$auctionpool->findByAttributes(array('auction_id' => $request['auction_id']));
                    if(!empty($auctionpool_data)){
                        $winner_id = $auctionpool_data->winner_id;
                    }
                    else{
                        $winner_id = $auctioninfo_data->winner_id;
                    }
                }
                else if($auctioninfo_data->status==2){
                    $winner_id = $auctioninfo_data->winner_id;
                }
                
                if($winner_id!=$customerId){
                    $bids=new CustomerBidAuctionCount();
                    $bids_data=$bids->findByPk($request['auction_id'].':'.$customerId.':CASH');
                    if(!empty($bids_data)){
                        if($bids_data->bid_num>0){
                            $order=new Orders();
                            $order_data=$order->findByAttributes(array('auction_id' => $request['auction_id'], 'customer_id' => $customerId , 'status' => 5));
                            if(empty($order_data)){
                                $result_array = array('success'=>1);
                            }else{
                                $result_array = array('error'=>'You have already processed buy it now.');//买过了
                            }                            
                        }
                        else{
                         $result_array = array('error'=>'You must place at least one bid on the auction to Buy Now. ');//你没有BID过   
                        }
                    } 
                    else{
                        $result_array = array('error'=>'You must place at least one bid on the auction to Buy Now. ');//你没有BID过
                    }                   
                }else{
                    $result_array = array('error'=>'You are currently winning this auction. Please wait for the other bidder(s)');//你是当前胜利者
                }
            }
        }
        echo json_encode($result_array);
    }
    
    public function actionAjaxBidAuction(){
        Yii::import('dao.bidAuction.BidAuction');
        
        $bidAuctionAjax = new BidAuctionAjax();
        if(!empty(Yii::app()->cache->get('mark_'.Yii::app()->user->id))){
            echo "<script>alert('You have been logged out')</script>";
//             Yii::app()->user->logout(true);
        }
        $bidAuctionAjax->setRequest($_POST);
        $bidAuctionAjax->customerId = Yii::app()->user->id;
        if (Yii::app()->user->isGuest){
            $bidAuctionAjax->setResponse('isGuest','Bid Auction need Login');
            echo $bidAuctionAjax->response();
            return ;
        }
        if ($bidAuctionAjax->validate()){
            $bidAuction = new BidAuction();
            $bidAuction->auctionId = $bidAuctionAjax->auctionId;
            $bidAuction->customerId = $bidAuctionAjax->customerId;
            $bid = $bidAuction->bid();
            if (!$bid){
                $errors = $bidAuction->getErrors();
                if (array_key_exists('overcost', $errors)){
                    $bidAuctionAjax->setResponse('overcost', $bidAuctionAjax->auctionId);
                }
                $errorMessages = array_shift($errors);
                $bidAuctionAjax->setResponse('error',"eGunner says:"."\n".$errorMessages[0]);
            }
        }else{
            $errors = $bidAuctionAjax->getErrors();
            $errorMessages = array_shift($errors);
            $bidAuctionAjax->setResponse('error',"eGunner says:"."\n".$errorMessages[0]);
        }
        echo $bidAuctionAjax->response();
    }
    public function actionAjaxWatch(){
        if(Yii::app()->user->isGuest){
            die;
        }
        $watch=new WatchAjax();
        $watch->setRequest($_POST);
        $watch->customerId=Yii::app()->user->id;

        if($watch->validate()){
            $favorites=new Favorites();
            $favorites_data=$favorites->findByAttributes(array('customer_id'=>$watch->customerId,'auction_id' => $watch->auctionId));
            if(!empty($favorites_data)){
                $favorites_data->enable=1;
                $watch_aucton=$favorites_data->save();
            }
            else{
                $favorites->customer_id=$watch->customerId;
                $favorites->auction_id=$watch->auctionId;
                $favorites->created_time=time();
                $favorites->enable=1;
                $watch_aucton=$favorites->save();
             }
            if(!$watch_aucton){
                $errors=$favorites->getErrors();
                $errorMessages = array_shift($errors);
                $watch->setResponse('error',$errorMessages[0]);
            }
        }
        else{
            $errors=$watch->getErrors();
            $errorMessages = array_shift($errors);            
            $watch->setResponse('error',$errorMessages[0]);

        }
        echo $watch->response();
    }
    public function actionAjaxCancelWatch(){
        if(Yii::app()->user->isGuest){
            die;
        }
        $watch=new WatchAjax();
        $watch->setRequest($_POST);
        $watch->customerId=Yii::app()->user->id;

        if($watch->validate()){
            $favorites=new Favorites();
            $favorites_data=$favorites->findByAttributes(array('customer_id'=>$watch->customerId,'auction_id' => $watch->auctionId));
            $favorites_data->enable=0;
            $cancel_aucton=$favorites_data->save();
            if(!$cancel_aucton){
                $errors=$favorites->getErrors();
                $errorMessages = array_shift($errors);
                $watch->setResponse('error',$errorMessages[0]);
            }
        }
        else{
            $errors=$watch->getErrors();
            $errorMessages = array_shift($errors);            
            $watch->setResponse('error',$errorMessages[0]);

        }
        echo $watch->response();
    }
    public function actionAjaxCouponCodeValid(){
        $couponCode = Yii::app()->request->getParam('couponCode',null);
        $couponCodeValidService = new CouponCodeVerificationService();
        $return = $couponCodeValidService->setCouponCode($couponCode)->setCouponCodeData()->verification();
        if($return){
            echo 1;
        }else{
            echo json_encode($couponCodeValidService->getErrorMessage());
        }
        
    }
    
    /**
     * 关闭新手帮助banner
     */
    public function actionClosenewins(){
        $data=$_GET;
        $response=array('result'=>false);
        if (Yii::app()->user->isGuest){
             echo json_encode($response);die;
        }
        if (array_key_exists("close", $data) && $data['close']){
            $customerInfo=new CustomerInfo();
            $customerInfo=$customerInfo->findByAttributes(array(
                'customer_id'=>Yii::app()->user->id,
            ));
            $customerInfo->close_newuser_ins=1;
            if ($customerInfo->save()){
                $response['result']=true;
            }else{
                $response['error']=$customerInfo->getErrors();
            }
        }
        echo json_encode($response);
    }
}